import React,{useState,useEffect,useRef} from 'react'
import { Space, Table, Modal, Button, Form, Input, message, Popconfirm, Select, notification } from 'antd';
import { WarningOutlined } from '@ant-design/icons';
import { getUserApi, searchUserApi, deleteUserApi, groupSearchApi, getUserTotalApi, updateUserApi, addUserApi } from '@/request/usermanagment'
import { addUserLoginApi } from '@/request/logmanagment.js'
import '@/assets/less/usermanagment.less'
import { usercolumns, department, roles } from '@/assets/data/common.js'
import cookie from 'react-cookies';

function UserManagment() {
  const [userList, setData] = useState([])
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0})
  const [load, setLoad] = useState(false)
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [addUserVisible, setAddUserVisible] = useState(false);
  const [userTotal, setUserTotal] = useState(0)   //用户总数
  const [value, setValue] = useState()   //搜索词
  const [pageLoad, setPageLoad] = useState(false)   //搜索词
  //数据搜索
  const { Search } = Input;
  const [form] = Form.useForm();

  /* 日志参数 */
  const logparams = useRef({
    id: '',
    username: "",
    function_module: "",
    search_condation: "",
    handle: ""
  })

  /* 获取用户信息 */
  let userInfo = cookie.load("userInfo")
  useEffect(()=>{
    logparams.current.id=userInfo.id
    logparams.current.username = userInfo.username
    getUserData(pagination.current, pagination.pageSize)
    operation()
  }, [])

  /* 角色判断 */
  const roleJudge =()=>{
    if (userInfo.role === 0) {
      notification.open({
        message: '你没有该权限，请联系管理员',
        icon: <WarningOutlined style={{ color: "#e5e517" }} />
      });
      return false
    }
    return true
  }

  /* 获取用户数据 */
  const getUserData = (current, pageSize)=>{
    setPageLoad(true)
    getUserTotalApi().then(res => {
      let userTotal =  res.data.length
      setPagination({ current, pageSize, total: userTotal })
      setUserTotal(userTotal)
      getUserApi(current, pageSize).then(res => {
        setData(res.data)
        setPageLoad(false)
      })
    })
  }

  /* 搜索词 */
  const keyWords = (e) => {
    setValue(e.target.value)
  }  

  /* 搜索 */
  const onSearch = (value, event) => {
    setLoad(true)
    searchUserApi(value).then(res=>{
      setData(res.data)
      setPagination({ current: 1, pageSize: 10, total: res.data.length })
      logRecord(value, "姓名/身份证/手机号查询")
    })
    setTimeout(() => {
      setLoad(false)
      setValue("")   //清空输入框
    }, 1000);
  }


  
  const groupchangehHandle =(value)=>{
    if(value.length===0){   //清除所有分组
      getUserData(1,30)   
    }else{
      groupSearchApi(value).then(res => {
        setData(res.data)
        setPagination({ current: 1, pageSize: 30, total: res.data.length })
        /* 日志记录 */
        logRecord(value.join(","), "部门查询")
      })
    }
  }

  /* 编辑 */
  const showModal = (record, index) => {
    if (!roleJudge()) return
    record.role === 0 ? record.role = "普通用户" : record.role = "管理员"
    setIsModalVisible(true);
    form.setFieldsValue(record)
  };

  const updatehandleOk = () => {
    //获取修改后的数据
    let userData = form.getFieldsValue()
    updateUserApi(userData).then(res => {
     message.success(res.message)
     setIsModalVisible(false);
      getUserData(pagination.current, pagination.pageSize)
      logRecord("", "编辑用户数据")
    })
   
  };
  const updatehandleCancel = (value) => {
    setIsModalVisible(false);
  };

  /* 添加 */
  const ShowAddHandle=()=>{
    if (!roleJudge()) return
    setAddUserVisible(true)
  }

  const addhandleOk=()=>{
    let addUser = form.getFieldsValue()
    addUserApi(addUser).then(res=>{
      if(res.code){
        message.success(res.message)
        getUserData(pagination.current, pagination.pageSize)
        logRecord("", "添加用户数据")
      }else{
        message.error(res.message)
      }
      setAddUserVisible(false);
      
    })
  }
  const addhandleCancel = ()=>{
    setAddUserVisible(false);
    form.resetFields()
  }

  /*  删除  */
  const delFn = (id) => {
    if (!roleJudge()) return
    deleteUserApi(id).then(res=>{
      message.success('删除成功')
      setTimeout(() => {
        getUserData(1,10)
        logRecord("","删除用户数据")
      }, 1500);
    })
  }

  /* 页数改变 */
  const pageChange = (data)=>{
    logRecord("", `页面跳转到${data.current}页，页面大小为${data.pageSize}`)
    if (data.total === userTotal) { 
      getUserData(data.current, data.pageSize)  //判断是否是搜索
    }
      setPagination(data)
  }
  

  /* 操作行 */
  const operation = ()=>{
    let operationObj = usercolumns[usercolumns.length-1]
    operationObj['render'] = (_, record, index) => (
      <Space size="middle">
        {/* text.key就是id */}
        <Button type='primary' onClick={() => showModal(record, index)}>编辑</Button>
        <Popconfirm title="确认删除?" okText="Yes" cancelText="No" onConfirm={() => delFn(record.id)}>
          <Button type='danger'>删除</Button>
        </Popconfirm>
      </Space>
    )
  }

  /* 日志记录 */
  const logRecord = (search,handle)=>{
    logparams.current = {
      ...logparams.current,
      function_module: localStorage.getItem("pathname"),
      search_condation: search,
      handle: handle
    }
    addUserLoginApi(logparams.current).then(res => { })
  }
  return (
    <div className='user_managment'>
      <div className='header'>
        <div className='search'>
          <Select
            mode="multiple"
            placeholder='请选择部门'
            showArrow
            onChange={groupchangehHandle}
            style={{
              minWidth: 260,
              height: 35,
              marginRight:20
            }}
            options={department}
          />
          <Search
            onSearch={onSearch}
            onChange={keyWords}
            value={value}
            loading={load}
            placeholder="根据姓名/身份证号/手机号进行检索"
            style={{
              width: '280px'
            }}
          />
        </div>
        <button className='add_user' onClick={ShowAddHandle}>添加用户</button>
      </div>
      <div className='table'>
        <Table
          columns={usercolumns}
          dataSource={userList}
          onChange={pageChange}
          pagination={pagination}
          loading={pageLoad}
        />
      </div>
      <Modal title="编辑用户资料" visible={isModalVisible} onOk={updatehandleOk}
        onCancel={updatehandleCancel}
        okText="确定" cancelText="取消">
        <Form
          form={form}
          name="basic"
          labelCol={{ span: 4 }}
          autoComplete="off"
        >
          <Form.Item
            //隐藏该字段 
            hidden='true'
            label="用户id"
            name="id"
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="用户名"
            name="username"
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="身份证号"
            name="id_card"
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="电话号码"
            name="phone"
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="部门"
            name="department"
          >
            <Select
              placeholder='请选择部门'
              showArrow
              listHeight={100}
              options={department}
            />
          </Form.Item>
          <Form.Item
            label="角色"
            name="role"
          >
            <Select
              placeholder='请选择角色'
              showArrow
              options={roles}
            />
          </Form.Item>

        </Form>
      </Modal>

      <Modal title="添加用户" visible={addUserVisible} onOk={addhandleOk}
        onCancel={addhandleCancel}
        okText="确定" cancelText="取消">
        <Form
          form={form}
          name="basic"
          labelCol={{ span: 4 }}
          autoComplete="off"
        >
          <Form.Item
            //隐藏该字段 
            hidden='true'
            label="用户id"
            name="id"
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="用户名"
            name="username"
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="身份证号"
            name="id_card"
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="电话号码"
            name="phone"
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="部门"
            name="department"
          >
            <Select
              placeholder='请选择部门'
              showArrow
              listHeight={100}
              options={department}
            />
          </Form.Item>
          <Form.Item
            label="角色"
            name="role"
          >
            <Select
              placeholder='请选择角色'
              showArrow
              options={roles}
            />
          </Form.Item>

        </Form>
      </Modal>
    </div>
  )
}

export default UserManagment
